function DataArrangement

%% Arrange trade data into n-times-m panel; i = importer; j = exporter
load SST_panel_vectorized;

ii = 1; 
for i=min(importer):max(importer),
    
    jj = 1;
    
    % openn = open but is defined because `open' is a Matlab command
    
    for j=min(exporter):max(exporter),
        x = border(importer==i & exporter==j); if isempty(x)==0, BORDER(ii,jj) = x; else BORDER(ii,jj) = -999; end; % common border dummy
        x = colony(importer==i & exporter==j); if isempty(x)==0, COLONY(ii,jj) = x; else COLONY(ii,jj) = -999; end; % colonial-tie dummy
        x = comfrt(importer==i & exporter==j); if isempty(x)==0, COMFRT(ii,jj) = x; else COMFRT(ii,jj) = -999; end; % share a PTA
        x =  openn(importer==i & exporter==j); if isempty(x)==0,   OPEN(ii,jj) = x; else   OPEN(ii,jj) = -999; end; % one of them is in a PTA
        x =  trade(importer==i & exporter==j); if isempty(x)==0,  TRADE(ii,jj) = x; else  TRADE(ii,jj) = -999; end; % trade volume
        x = comlng(importer==i & exporter==j); if isempty(x)==0, COMLNG(ii,jj) = x; else COMLNG(ii,jj) = -999; end; % common-language dummy
        x = lndist(importer==i & exporter==j); if isempty(x)==0, LNDIST(ii,jj) = x; else LNDIST(ii,jj) = -999; end; % log distance 
          
        x = comfrt_wto(importer==i & exporter==j); if isempty(x)==0, COMFRT_WTO(ii,jj) = x; else COMFRT_WTO(ii,jj) = -999; end; % share a PTA - WTO
        x =   open_wto(importer==i & exporter==j); if isempty(x)==0,   OPEN_WTO(ii,jj) = x; else   OPEN_WTO(ii,jj) = -999; end; % one of them is in a PTA - WTO
        
        jj = jj+1; 
         
    end  
    
    ii = ii+1;
end

clear border colony comfrt comlng exporter importer i ii j jj lndist open openn trade x open_wto comfrt_wto;

save SST_panel_1; % still contains countries for which all data is -999: all variables are dimension 205-times-205

%% Delete countries that do not import or do not export
for i=1:205, 
    no_import(i) = sum(TRADE(i,:))==(-999*205); 
    no_export(i) = sum(TRADE(:,i))==(-999*205); 
end

BORDER(no_import==1,:) = []; BORDER(:,no_export==1) = [];
COLONY(no_import==1,:) = []; COLONY(:,no_export==1) = [];
COMFRT(no_import==1,:) = []; COMFRT(:,no_export==1) = [];
COMLNG(no_import==1,:) = []; COMLNG(:,no_export==1) = [];
LNDIST(no_import==1,:) = []; LNDIST(:,no_export==1) = [];
  OPEN(no_import==1,:) = [];   OPEN(:,no_export==1) = [];
 TRADE(no_import==1,:) = [];  TRADE(:,no_export==1) = [];
 
  OPEN_WTO(no_import==1,:) = [];   OPEN_WTO(:,no_export==1) = [];
COMFRT_WTO(no_import==1,:) = []; COMFRT_WTO(:,no_export==1) = [];
 
clear i no_import no_export;
 
save SST_panel_3;



